#include "imageset.h"

#include <stdlib.h>
#include <string.h>

char* unused = "unused";

Imageset* imageset_new()
{
	int i;

	Imageset* is = calloc(1, sizeof(Imageset));
	is->images = NULL;
	is->n_images = 0;
	for(i=0; i<256; i++)
	{
		is->color[i].r = is->color[i].g = is->color[i].b = 0;
		is->color[i].name = unused;
	}
	imageset_setcolor(is, 0x00, 0x00, 0x00, 0x00, "black");
	imageset_setcolor(is, 0xfe, 0xfe, 0xfe, 0xfe, "white");
	imageset_setcolor(is, 0xff, 0xff, 0xff, 0xff, "transparent");

	return is;
}


void imageset_setcolor(Imageset* is, uint8_t color, 
		uint8_t r, uint8_t g, uint8_t b, char* name)
{
	if(is->color[color].name != unused)
		free(is->color[color].name);
	is->color[color].name = strdup(name);
	is->color[color].r = r;
	is->color[color].g = g;
	is->color[color].b = b;
}


Image* imageset_addimage(Imageset* is, uint16_t w, uint16_t h, char* name)
{
	Image* img = image_new((struct Imageset*)is, w, h, name);

	int i=0;
	for(i=0; i<(w*h); i++)
		img->data[i] = 0xff;

	is->n_images++;
	is->images = realloc(is->images, sizeof(Image) * is->n_images);
	is->images[is->n_images-1] = img;

	return img;
}


int imageset_deleteimage(Imageset* is, uint16_t n)
{
	int i;
	if(n >= is->n_images)
		return 0;

	Image* img = is->images[n];
	for(i=n; i<is->n_images-1; i++)
		is->images[i] = is->images[i+1];
	is->n_images--;
	is->images = realloc(is->images, sizeof(Image) * is->n_images);

	image_free(img);

	return -1;
}


void imageset_output(Imageset *is, FILE* f)
{
	int i;

	fprintf(f, "imageset {\n\n");
	fprintf(f, "  colormap {\n");
	for(i=0; i<=0xfe; i++)
		if(is->color[i].name != unused)
			fprintf(f, "    %02x : \"%s\" [ %02x %02x %02x ]\n",
					i, is->color[i].name, is->color[i].r,
					is->color[i].g, is->color[i].b);
	fprintf(f, "  }\n\n");
	for(i=0; i<is->n_images; i++)
	{
		Image* img = is->images[i];
		fprintf(f, "  image {\n");
		fprintf(f, "    name \"%s\"\n", img->name);
		fprintf(f, "    width %d\n", img->w);
		fprintf(f, "    height %d\n", img->h);
		fprintf(f, "    data {\n");
		int j;
		for(j=0; j<(img->w * img->h); j++)
		{
			if(j % img->w == 0)
				fprintf(f, "      ");
			fprintf(f, "%02x ", img->data[j]);
			if(j % img->w == img->w-1)
				fprintf(f, "\n");
		}
		fprintf(f, "    }\n");
		fprintf(f, "  }\n\n");
	}
	fprintf(f, "}\n");
}


void imageset_delete(Imageset* is)
{
	int i;
	for(i=(is->n_images-1); i>=0; i--)
		imageset_deleteimage(is, i);
	for(i=0; i<256; i++)
		if(is->color[i].name != unused)
			free(is->color[i].name);
	free(is);
}
